/*
 * @Author: Drc
 * @Date: 2020-06-17 15:31:56
 * @LastEditors: Drc
 * @LastEditTime: 2021-11-01 18:32:08
 */
import React from 'react'
import {
  TextInput,
  TextInputProps,
  View,
  Platform,
  TextStyle,
  Pressable,
  TouchableOpacityProps,
  PressableProps,
  ViewProps,
  ViewStyle,
  TouchableOpacity,
  Image,
} from 'react-native'
import ThemeText from '@path/components/ThemeComponents/ThemeText'
import Theme from '@path/config/theme'
import System, {px2dp} from '@path/config/system'
import Locale from '@path/locale'
import {RFValue} from 'react-native-responsive-fontsize'

type LayoutStyle = 'deepin'

export interface ThemeTextInputProps extends TextInputProps {
  containerStyle?: ViewStyle
  leftComponent?: JSX.Element | undefined
  rightComponent?: JSX.Element | undefined
  headerComponent?: JSX.Element | undefined
  footerComponent?: JSX.Element | undefined
  headerText?: string
  footerText?: string
  headerTextStyle?: TextStyle
  footerTextStyle?: TextStyle
  isError?: boolean
  onPress?: Function
  decimalLimit?: number
  layoutStyle: LayoutStyle
  isShowControl?: boolean //是否显示“控制显示”（小眼睛）
}

class ThemeTextInput extends React.Component<ThemeTextInputProps> {
  constructor(props: any) {
    super(props)
  }

  static defaultProps: ThemeTextInputProps = {
    layoutStyle: 'deepin',
    containerStyle: {},
    leftComponent: undefined,
    rightComponent: undefined,
    headerComponent: undefined,
    footerComponent: undefined,
    headerText: '',
    footerText: '',
    headerTextStyle: {},
    footerTextStyle: {},
    isError: false,
  }

  state = {
    secureTextEntry: this.props.secureTextEntry,
  }

  _renderLeft = () => {
    return this.props.leftComponent || null
  }

  _renderRight = () => {
    return this.props.rightComponent || (this.props.isShowControl && this._renderShowControl()) || null
  }

  _renderHeader = () => {
    if (this.props.headerComponent) {
      return this.props.headerComponent
    } else if (this.props.headerText) {
      return (
        <ThemeText
          style={{
            fontSize: 14,
            color: Theme.getThemeColor('text_label'),
            ...this.props.headerTextStyle,
          }}>
          {this.props.headerText}
        </ThemeText>
      )
    } else {
      return null
    }
  }

  _renderFooter = () => {
    if (this.props.footerComponent) {
      return this.props.footerComponent
    } else if (this.props.footerText) {
      return (
        <ThemeText
          style={{
            color: this.props.isError ? Theme.getThemeColor('error') : Theme.getThemeColor('text_minor'),
            fontSize: 14,
            marginTop: px2dp(15),
            ...this.props.footerTextStyle,
          }}>
          {this.props.footerText}
        </ThemeText>
      )
    } else {
      return null
    }
  }

  _renderShowControl = () => {
    return (
      <TouchableOpacity
        hitSlop={{bottom: 5, left: 5, right: 5, top: 5}}
        activeOpacity={1}
        onPress={() => {
          this.setState({secureTextEntry: !this.state.secureTextEntry})
        }}>
        <Image
          style={{width: px2dp(16), height: px2dp(16)}}
          source={this.state.secureTextEntry ? Locale.getImage('eye_close') : Locale.getImage('eye_open')}
        />
      </TouchableOpacity>
    )
  }

  WrappedContainer = (props: ViewProps | TouchableOpacityProps | PressableProps) => {
    if (this.props.onPress) {
      return Platform.OS === 'android' ? (
        <Pressable {...props}>{props?.children}</Pressable>
      ) : (
        <TouchableOpacity {...props}>{props?.children}</TouchableOpacity>
      )
    } else {
      return <View {...props}>{props?.children}</View>
    }
  }

  render() {
    const {containerStyle, layoutStyle, decimalLimit, isError, ...other} = this.props
    const defaultInputProps = {
      deepin: {
        placeholderTextColor: Theme.getThemeColor('holder'),
        clearButtonMode: 'while-editing',
        style: {
          includeFontPadding: false,
          color: isError ? Theme.getThemeColor('error') : Theme.getThemeColor('text_main'),
          padding: 0,
          paddingTop: Platform.OS === 'android' ? px2dp(6 + 0.5) : px2dp(12 + 0.5),
          paddingBottom: Platform.OS === 'android' ? px2dp(6) : px2dp(12),
          flex: 1,
          fontSize: 12,
        },
      } as TextInputProps,
    }

    const defaultContainerStyle = {
      deepin: {
        borderBottomWidth: 0.5,
        borderBottomColor: Theme.getThemeColor('border'),
      } as ViewStyle,
    }

    return (
      <View style={containerStyle}>
        {this._renderHeader()}
        <this.WrappedContainer
          activeOpacity={1}
          disabled={!this.props.onPress}
          onPress={() => {
            typeof this.props.onPress === 'function' && this.props.onPress()
          }}
          style={{
            borderColor: this.props.isError ? Theme.getThemeColor('error') : 'transparent',
            flexDirection: 'row',
            alignItems: 'center',
            ...defaultContainerStyle[layoutStyle],
          }}>
          {this._renderLeft()}
          <TextInput
            {...defaultInputProps[layoutStyle]}
            {...other}
            style={{
              ...defaultInputProps[layoutStyle]?.style,
              ...other?.style,
              fontSize: RFValue(
                other?.style?.fontSize ?? defaultInputProps[layoutStyle]?.style?.fontSize,
                System.height,
              ),
            }}
            onChangeText={(text) => {
              if (decimalLimit === 0 && text?.includes('.')) {
                return
              }

              if (decimalLimit && text?.includes('.') && text.split('.')[1]?.length > decimalLimit) {
                return
              }
              typeof this.props.onChangeText === 'function' && this.props.onChangeText(text)
            }}
            secureTextEntry={this.state.secureTextEntry}
          />
          {this._renderRight()}
        </this.WrappedContainer>
        {this._renderFooter()}
      </View>
    )
  }
}

export default ThemeTextInput
